﻿using Asmodat.Abbreviate;
using Asmodat.Extensions.Collections.Generic;
using Asmodat.Extensions.Objects;
using Asmodat.IO;
using Asmodat.Types;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Asmodat_ELM
{
    public partial class Form1 : Form
    {
        private void TBtnSend_Click(object sender, EventArgs e)
        {
            Methods.Run(() => Submit(), null, true, true);
        }

        private void TTbxSubmit_OnThreadedEnterKeyDown(object source, KeyEventArgs e)
        {
            Methods.Run(() => Submit(), null, true, true);
        }

        public void Submit()
        {
            TTbxSubmit.Enabled = false;
            TBtnSend.Enabled = false;
            TTbxSubmit.BackColor = Color.LightGreen;
            TTbxSubmit.ForeColor = Color.White;
            this.Send(TTbxSubmit.Text, true, Color.DarkGreen);
            Thread.Sleep(100);
            TTbxSubmit.BackColor = Color.White;
            TTbxSubmit.ForeColor = Color.Black;
            TTbxSubmit.Enabled = true;
            TBtnSend.Enabled = true;
            TTbxSubmit.Focus();
        }


        public bool Send(string text, bool show = false, Color? textColor = null)
        {
            bool result = _serialPort.Send(text);

            if (show)
            {
                if (textColor == null) textColor = Color.DarkRed;

                Color color = result ? textColor.Value : Color.Red;
                TRtbxMain.AppendText(text + "\r\n", color, 5000);
                TRtbxMain.ScrollToEnd();
            }
            return result;
        }


        public string SyncBuffer { get; set; } = "";
        public bool SendSync(string text, int timeout_ms = 10000, int wekup_ms = 500, bool show = false, Color? textColor = null)
        {
            SyncBuffer = "";
            bool result = this.Send(text, show, textColor);

            bool contains = false;
            TickTimeout timeout = new TickTimeout(timeout_ms, TickTime.Unit.ms);

            while (result && _serialPort.IsOpen && !timeout.IsTriggered)
            {
                if (contains = SyncBuffer.Contains(text.TryTrim()))
                    break;
                else
                    Thread.Sleep(1);
            }

            return result && contains;
        }
    }
}
